package com.xqb.listen.ui.main

import androidx.activity.compose.BackHandler
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.Icon
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.Text
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ChainStyle
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import coil.compose.AsyncImage
import com.xqb.listen.R
import com.xqb.listen.manager.Constants
import com.xqb.listen.manager.MediaPlayManager
import com.xqb.listen.model.PlayStatus
import com.xqb.listen.navigation.NavParams
import com.xqb.listen.ui.theme.Transparent
import com.xqb.listen.ui.theme.White
import com.xqb.listen.ui.theme.White10
import com.xqb.listen.ui.theme.White15
import com.xqb.listen.ui.theme.White50
import com.xqb.listen.ui.theme.White80
import com.xqb.listen.ui.theme.page_bg_color
import com.xqb.listen.ui.theme.play_bar_color
import com.xqb.listen.utils.FastClickHandleUtil
import kotlinx.coroutines.launch

/**
 * author:17873
 * date:2024/4/2
 * des:MainPage
 **/

@Composable
fun MainPage(onSkipPage : (navParams: NavParams)-> Unit) {

    val drawerState = rememberDrawerState(DrawerValue.Closed)
    val pagerState = rememberPagerState(pageCount = {3})
    val scope = rememberCoroutineScope()
    val currentTabIndex = remember { mutableIntStateOf(1) }

    BackHandler(drawerState.isOpen) {
        if(drawerState.isOpen){
            scope.launch {
                drawerState.close()
            }
        }
    }

    ModalNavigationDrawer(
        drawerState = drawerState,
        drawerContent = {
            MainDrawerContent {
                when(it){
                    Constants.DRAWER_USER->{
                        if(drawerState.isOpen){
                            scope.launch {
                                drawerState.close()
                            }
                        }
                    }
                    Constants.DRAWER_SCAN->{

                    }
                }
            }
        }
    ){
        Column(
            Modifier
                .fillMaxSize()
                .navigationBarsPadding()
        ) {
            MainToolbar{
                if(drawerState.isClosed){
                    scope.launch {
                        drawerState.open()
                    }
                }
            }

            MainTab(height = 40.dp, tabIndex = currentTabIndex.value){
                if(currentTabIndex.value != it){
                    currentTabIndex.value = it
                    scope.launch {
                        pagerState.scrollToPage(it , 0f)
                    }
                }
            }

            HorizontalPager(
                state = pagerState,
                Modifier
                    .weight(1f)
                    .padding(top = 10.dp),
            ) {
                if(currentTabIndex.value !=  pagerState.currentPage){
                    println("---->${pagerState.currentPage}")
                    currentTabIndex.value = pagerState.currentPage
                }

                when(pagerState.currentPage){
                    1 -> {}
                    2 -> {}
                    else-> MusicPage(onSkipPage)
                }
            }

            MediaPlayManager.singleInstance.currentMedia?.let {

                val playState = MediaPlayManager.singleInstance.currentState.collectAsStateWithLifecycle()
                val rotateAnim = remember { Animatable(0f) }
                val context = LocalContext.current

                LaunchedEffect(playState.value) {
                    if(playState.value == PlayStatus.PLAY.name) {
                        rotateAnim.animateTo(
                            targetValue = 360f,
                            animationSpec = infiniteRepeatable(
                                animation = tween(3000, easing = LinearEasing),
                                repeatMode = RepeatMode.Restart
                            ))
                    }else{
                        rotateAnim.animateTo(0f)
                        rotateAnim.stop()
                    }
                }

                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .shadow(20.dp, shape = RoundedCornerShape(0.dp))
                        .height(55.dp)
                        .background(play_bar_color)
                        .padding(start = 20.dp, end = 15.dp),

                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Box(
                        Modifier
                            .background(White10, shape = CircleShape)
                            .padding(5.dp)
                    ){
                        Image(
                            painter = painterResource(id = R.drawable.ic_app_icon_bar),
                            contentDescription = null,
                            modifier = Modifier
                                .size(35.dp)
                                .background(
                                    White15,
                                    shape = CircleShape,
                                )
                                .rotate(rotateAnim.value),
                        )
                    }
                    Spacer(modifier = Modifier.width(10.dp))
                    Text(
                        text = it.filename,
                        color = White,
                        fontSize = 13.sp,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                        fontWeight = FontWeight.Medium,
                        modifier = Modifier.weight(1f)
                    )
                    Spacer(modifier = Modifier.width(30.dp))
                    Icon(
                        painter = painterResource(id = if(playState.value == PlayStatus.PLAY.name) R.drawable.ic_play else R.drawable.ic_pause),
                        contentDescription = null ,
                        tint = White,
                        modifier = Modifier
                            .size(44.dp)
                            .clip(CircleShape)
                            .clickable {
                                if(FastClickHandleUtil.isFastClick(500)) return@clickable
                                if(playState.value == PlayStatus.PLAY.name){
                                    MediaPlayManager.singleInstance.pauseAudio(context, true)
                                }else{
                                    MediaPlayManager.singleInstance.resumeAudio(context , true)
                                }
                            }
                    )
                    Icon(
                        painter = painterResource(id = R.drawable.ic_queue),
                        contentDescription = null ,
                        tint = White,
                        modifier = Modifier
                            .size(44.dp)
                            .alpha(0.6f)
                            .clip(CircleShape)
                            .clickable {

                            }
                    )
                }
            }
        }
    }
}

//侧拉栏
@Composable
fun MainDrawerContent(onDrawItemClick :(btn : String) -> Unit){
    ModalDrawerSheet(
        drawerContainerColor = page_bg_color,
        modifier = Modifier
            .fillMaxHeight()
            .width(288.dp)
    ) {

        val interactionSource = remember { MutableInteractionSource() }

        Row(
            Modifier.padding(top = 6.dp, start = 15.dp, end = 15.dp),
            verticalAlignment = Alignment.CenterVertically
        ){

            AsyncImage(
                model = "https://image.res.meizu.com/image/uc/b1529e4d53649185c5cbeca96d4cae71/w200h200",
                contentDescription = null,
                Modifier
                    .size(28.dp)
                    .border(1.dp, White50, CircleShape)
                    .clip(CircleShape)
                    .clickable(
                        indication = null,
                        interactionSource = interactionSource
                    ) {
                        onDrawItemClick(Constants.DRAWER_USER)
                    }
            )
            Text(
                text = "甜瓜旁的长白山",
                fontSize = 15.sp,
                color = White,
                modifier = Modifier
                    .padding(start = 10.dp)
                    .clickable(
                        indication = null,
                        interactionSource = interactionSource
                    ) {
                        onDrawItemClick(Constants.DRAWER_USER)
                    }
            )
            Image(
                painter = painterResource(R.drawable.ic_next_action),
                contentDescription = null,
                Modifier
                    .size(14.dp)
                    .padding(start = 5.dp)
            )
            Spacer(Modifier.weight(1f))

            Image(
                painter = painterResource(R.drawable.ic_scan),
                contentDescription = null,
                Modifier.clickable(
                    indication = null,
                    interactionSource = interactionSource
                ) {
                    onDrawItemClick(Constants.DRAWER_SCAN)
                }
            )
        }
    }
}

//主页顶部
@Composable
fun MainToolbar(onMenuClick :() -> Unit) {
    ConstraintLayout(
        Modifier
            .fillMaxWidth()
            .height(230.dp)
    ) {

        val (toolMenu , toolIcon , toolName , toolInfo , toolSex , toolMask) = createRefs()
        createVerticalChain(toolName , toolInfo , chainStyle = ChainStyle.Packed)

        Image(
            painter = painterResource(R.drawable.img_usre_bg),
            contentDescription = null,
            Modifier
                .fillMaxSize()
                .alpha(0.8f),
            contentScale = ContentScale.Crop
        )

        Box(
            Modifier
                .fillMaxWidth()
                .height(70.dp)
                .background(Brush.verticalGradient(arrayListOf(Transparent, page_bg_color)))
                .constrainAs(toolMask) {
                    bottom.linkTo(parent.bottom)
                }
        )

        AsyncImage(
            model = "https://image.res.meizu.com/image/uc/b1529e4d53649185c5cbeca96d4cae71/w200h200",
            contentDescription = null,
            Modifier
                .padding(start = 25.dp, top = 50.dp)
                .size(50.dp)
                .border(1.dp, White50, CircleShape)
                .clip(CircleShape)
                .constrainAs(toolIcon) {
                    top.linkTo(parent.top)
                    start.linkTo(parent.start)
                    bottom.linkTo(parent.bottom)
                }
        )

        Text(
            text = "甜瓜旁的长白山",
            color = White,
            fontSize = 18.sp,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
            fontWeight = FontWeight.Bold,
            modifier = Modifier
                .padding(start = 10.dp, end = 80.dp, top = 50.dp)
                .constrainAs(toolName) {
                    start.linkTo(toolIcon.end)
                    end.linkTo(parent.end)
                    top.linkTo(toolIcon.top)
                    bottom.linkTo(toolInfo.top)
                    width = Dimension.fillToConstraints
                }
        )

        Text(
            text = "大抵知心有庭树，亭亭一如你风致。",
            color = White80,
            fontSize = 10.sp,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
            modifier = Modifier
                .padding(start = 2.dp, end = 80.dp)
                .constrainAs(toolInfo) {
                    linkTo(
                        start = toolSex.end,
                        end = parent.end,
                        top = toolName.bottom,
                        bottom = toolIcon.bottom
                    )
                    width = Dimension.fillToConstraints
                }
        )

        Image(
            painter = painterResource(R.drawable.ic_boy),
            contentDescription = null,
            Modifier
                .padding(start = 10.dp)
                .size(15.dp)
                .constrainAs(toolSex) {
                    top.linkTo(toolInfo.top)
                    bottom.linkTo(toolInfo.bottom)
                    start.linkTo(toolIcon.end)
                }
        )



        Image(
            painter = painterResource(R.drawable.ic_menu),
            contentDescription = null,
            Modifier
                .systemBarsPadding()
                .padding(start = 10.dp)
                .clip(CircleShape)
                .constrainAs(toolMenu) {
                    top.linkTo(parent.top)
                    start.linkTo(parent.start)
                }
                .clickable {
                    onMenuClick()
                }
        )
    }
}

@Composable
fun MainTab(height : Dp = 52.dp, tabIndex : Int, onTabClick :(position : Int) -> Unit){

    ConstraintLayout(
        Modifier
            .fillMaxWidth()
            .height(height),
    ) {
        val (tab1 , tab2 , tab3 , tabIndicator) = createRefs()

        Text(
            stringResource(R.string.tab_1) ,
            fontWeight = if(tabIndex == 0) FontWeight.Bold else FontWeight.Normal,
            fontSize = if(tabIndex == 0) 18.sp else 17.sp,
            color = if(tabIndex == 0) White else White80,
            modifier = Modifier
                .padding(start = 20.dp)
                .clickable { onTabClick(0) }
                .constrainAs(tab1) {
                    centerVerticallyTo(parent)
                    start.linkTo(parent.start)
                },
        )

        Text(
            stringResource(R.string.tab_2) ,
            fontWeight = if(tabIndex == 1) FontWeight.Bold else FontWeight.Normal,
            fontSize = if(tabIndex == 1) 18.sp else 17.sp,
            color = if(tabIndex == 1) White else White80,
            modifier = Modifier
                .padding(start = 20.dp)
                .clickable { onTabClick(1) }
                .constrainAs(tab2) {
                    centerVerticallyTo(parent)
                    start.linkTo(tab1.end)
                }
        )
        Text(
            stringResource(R.string.tab_3) ,
            fontWeight = if(tabIndex == 2) FontWeight.Bold else FontWeight.Normal,
            fontSize = if(tabIndex == 2) 18.sp else 17.sp,
            color = if(tabIndex == 2) White else White80,
            modifier = Modifier
                .padding(start = 20.dp)
                .clickable { onTabClick(2) }
                .constrainAs(tab3) {
                    centerVerticallyTo(parent)
                    start.linkTo(tab2.end)
                }
        )

        Box(
            Modifier
                .height(2.dp)
                .padding(start = 30.dp, end = 10.dp)
                .background(White, RoundedCornerShape(2.dp))
                .constrainAs(tabIndicator) {
                    bottom.linkTo(parent.bottom)
                    centerHorizontallyTo(if (tabIndex == 0) tab1 else if (tabIndex == 1) tab2 else tab3)
                    width = Dimension.fillToConstraints
                }
        )
    }
}

@Preview(showSystemUi = true , showBackground = true )
@Composable
fun MainPagePreview(){
//    MainToolbar{}
//    MainToolbar {}
    MainPage {

    }
}